package top.jybill.service.Impl;

import com.github.pagehelper.PageHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import top.jybill.dao.IPermissionDao;
import top.jybill.dao.IRolePermissionDao;
import top.jybill.domain.MyPageInfo;
import top.jybill.domain.Permission;
import top.jybill.service.IPermissionService;
import top.jybill.utils.CharCodeUtil;

import java.util.List;

@Service
@Transactional(readOnly = true, propagation = Propagation.SUPPORTS)
public class PermissionServiceImpl implements IPermissionService {
  @Autowired
  private IPermissionDao permissionDao;
  @Autowired
  private IRolePermissionDao rolePermissionDao;


  /**
   * 根据角色id查询该下的所有权限
   * @param roleId
   * @return
   */
  public List<Permission> findPermissionsByrid(String roleId) {
    List<Permission> permissions = permissionDao.findPermissionsByRoleId(roleId);
    if (permissions.size() < 1) {
      permissions = null;
    }
    return permissions;
  }

  /**
   * 获取所有权限
   * @return
   */
  public List<Permission> findAllPermissions() {
    return permissionDao.findAllPermissions();
  }

  /**
   * 分页查询权限
   * @param page
   * @return
   */
  public MyPageInfo findPermissionsByPage(MyPageInfo page) {
    page.setQuery(CharCodeUtil.getUTF8CharCode(page.getQuery(), "UTF-8"));

    // query校验
    if (page.getQuery() == null || page.getQuery().length() < 1 || "null".equalsIgnoreCase(page.getQuery())) {
      page.setQuery(null);
    } else {
      page.setQuery("%" + page.getQuery() + "%");
    }

    // 设置分页
    PageHelper.startPage(page.getPageNum(), page.getPageSize());
    MyPageInfo retPage = new MyPageInfo(permissionDao.findPermissionsByPage(page));
    retPage.setPageNum(page.getPageNum());
    retPage.setPageSize(page.getPageSize());
    return retPage;
  }

  /**
   *
   * @param permission
   */
  @Transactional(readOnly = false, propagation = Propagation.REQUIRED)
  public void addPermission(Permission permission) {
    System.out.println(permission);
    permissionDao.addPermission(permission);
  }

  /**
   * 更新权限
   * @param permission
   */
  @Transactional(readOnly = false, propagation = Propagation.REQUIRED)
  public void updatePermission(Permission permission) {
    permissionDao.updatePermission(permission);
  }

  /**
   * 删除权限
   * @param pid
   */
  @Transactional(readOnly = false, propagation = Propagation.REQUIRED)
  public void delPermission(String pid) {
    // 删除角色-权限关联
    rolePermissionDao.delPermissionRoleByPid(pid);

    // 删除权限
    permissionDao.delPermission(pid);
  }

  /**
   * 根据permission id查询permission
   * @param pid
   * @return
   */
  public Permission findPermissionByPid(String pid) {
    return permissionDao.findPermissionByPid(pid);
  }


}
